﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Web.Http;

namespace CommonBusBack.Controllers
{
    public class WeiXinController : ApiController
    {
        string token="jfyweixin";
        [HttpPost]
        [Route("api/WeiXin/jfyWeiXin")]
        public string Index(String signature, String timestamp, String nonce, String echostr)
        {
            string echoStr = echostr;
            if (CheckSignature(signature, timestamp, nonce))
            {
                if (!string.IsNullOrEmpty(echoStr))
                {
                    return echoStr;
                }
            }
            return "";
        }

    //signature、timestamp、nonce、echostr
        public bool CheckSignature(String signature, String timestamp, String nonce)
        {
            String[] arr = new String[] { token, timestamp, nonce };
            // 将token、timestamp、nonce三个参数进行字典序排序    
            Array.Sort<String>(arr);

            StringBuilder content = new StringBuilder();
            for (int i = 0; i < arr.Length; i++)
            {
                content.Append(arr[i]);
            }

            String tmpStr = SHA1_Encrypt(content.ToString());


            // 将sha1加密后的字符串可与signature对比，标识该请求来源于微信    
            return tmpStr != null ? tmpStr.Equals(signature) : false;
        }
        /// <summary>  
 /// 使用缺省密钥给字符串加密  
 /// </summary>  
 /// <param name="Source_String"></param>  
 /// <returns></returns>  
 public static string SHA1_Encrypt(string Source_String)  
 {  
     byte[] StrRes = Encoding.Default.GetBytes(Source_String);  
     HashAlgorithm iSHA = new SHA1CryptoServiceProvider();  
     StrRes = iSHA.ComputeHash(StrRes);  
     StringBuilder EnText = new StringBuilder();  
     foreach (byte iByte in StrRes)  
     {  
         EnText.AppendFormat("{0:x2}", iByte);  
     }  
     return EnText.ToString();  
 }



        // GET api/<controller>
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<controller>/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<controller>
        public void Post([FromBody]string value)
        {
        }

        // PUT api/<controller>/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/<controller>/5
        public void Delete(int id)
        {
        }
    }
}